package com.pzhu.gmall.file.controller;

import com.pzhu.gmall.annotation.EnableFastdfsClient;
import com.pzhu.gmall.service.FastdfsClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 刘鹏 liupeng
 * @date 2019/10/31
 **/
@RestController
@EnableFastdfsClient
@CrossOrigin
@RequestMapping("/fileUpload")
public class FileController {
    @Autowired
    private FastdfsClientService fastdfsClientService;

    @Value("${fastdfs.nginx-servers}")
    private String nginxServers;

    @Value("${url.header}")
    private String urlHeader;

    @PostMapping
    public String fileUpload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        String originalFilename = multipartFile.getOriginalFilename();
        String filesuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String[] url = fastdfsClientService.upload(multipartFile.getBytes(), filesuffix, null);
        StringBuilder stringBuilder = new StringBuilder(urlHeader + nginxServers);
        for (String s : url) {
            stringBuilder.append("/");
            stringBuilder.append(s);
        }
        return stringBuilder.toString();
    }
}
